package fr.nfan.android;

import android.app.Activity;
import android.os.Bundle;
import android.os.Vibrator;
import android.text.ClipboardManager;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.TextView;

public class TuneYourVibreActivity extends Activity {
    
	private VibratorCommand vibratorCommand;

	private long touch = 0;
	
	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        Vibrator vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
        vibratorCommand = new VibratorCommand(vibrator);
        
        
        
        Button recordBtn = (Button) findViewById(R.id.Record);
        recordBtn.setOnClickListener(new View.OnClickListener() {
			
			public void onClick(View v) {
				TextView patternText = (TextView) findViewById(R.id.PatternText);
				if (! vibratorCommand.isRecording()) {
					vibratorCommand.startRecord();
					patternText.setText("");
					touch = 0;
				} else {
					vibratorCommand.stopRecord();
					vibratorCommand.play();
					patternText.setText(vibratorCommand.getPattern());
				}
			}
		});
        
        ImageButton tuneBtn = (ImageButton) findViewById(R.id.TuneButton);
        tuneBtn.setOnTouchListener(new View.OnTouchListener() {
			
			public boolean onTouch(View v, MotionEvent event) {
				
				if (vibratorCommand.isRecording()) {
					if (event.getAction() == 0) { /* Press */
						if (touch != 0) {
							vibratorCommand.addVibe(event.getEventTime() - touch);
							touch = 0;
						}
						
					} else if (event.getAction() == 1) {
						vibratorCommand.addVibe(event.getEventTime() - event.getDownTime());
						touch = event.getEventTime();
					}
				}
				
				return false;
			}
		});
        
        Button playBtn = (Button) findViewById(R.id.Play);
        playBtn.setOnClickListener(new View.OnClickListener() {
			
			public void onClick(View v) {
				TextView patternText = (TextView) findViewById(R.id.PatternText);
				vibratorCommand.play(patternText.getText().toString());
			}
		});
        
        Button copyBtn = (Button) findViewById(R.id.Copy);
        
        copyBtn.setOnClickListener(new View.OnClickListener() {
			
			public void onClick(View v) {
				ClipboardManager clipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE); 
		        clipboard.setText(vibratorCommand.getPattern());
			}
		});
        
        
    }
}
